package com.ld.common.util;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ld.admin.model.system.SystemUser;
import com.ld.admin.service.user.LoginParams;
import com.ld.shieldsb.common.composition.util.SecurityUtil;
import com.ld.shieldsb.common.core.model.PropertiesModel;
import com.ld.shieldsb.common.core.util.DateUtil;
import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.shieldsb.common.web.util.WebUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LoginCookieUtil extends CookieUtil {
    private static final String LOGIN_COOKIE_NAME = "sclgoni";
    private static final String COOKIE_NAME_USERNAME = "username:";
    private static final String COOKIE_NAME_PASSWORD = "_password:";
    private static final String COOKIE_NAME_TIMEUTIL = "_timeutil";
    private static final String COOKIE_NAME_IP = "_ip:";

    /**
     * 增加登录cookie
     * 
     * @Title addLoginCookie
     * @author 吕凯
     * @date 2019年7月19日 下午5:50:04
     * @param response
     * @param expiry
     *            过期时间，单位秒
     * @param username
     * @param password
     *            void
     */
    public static void addLoginCookie(HttpServletRequest request, HttpServletResponse response, int expiry, String username,
            String password) {
        LoginParams params = new LoginParams();
        params.setMaxInactiveInterval(expiry);
        params.setUsername(username);
        params.setPassword(password);
        addLoginCookie(request, response, params);
    }

    public static void addLoginCookie(HttpServletRequest request, HttpServletResponse response, LoginParams params) {
        int expiry = params.getMaxInactiveInterval();
        String username = params.getUsername();
        String password = params.getPassword();
        String timeUtil = DateUtil.getDateTimeString(DateUtil.addDate(new Date(), expiry, Calendar.SECOND));
        String ip = WebUtil.getIpAddr(request);
        String scloginCookieVal = COOKIE_NAME_USERNAME + username + COOKIE_NAME_PASSWORD + password + COOKIE_NAME_TIMEUTIL + timeUtil
                + COOKIE_NAME_IP + ip;
        scloginCookieVal = SecurityUtil.simpleEncrypt(scloginCookieVal);
        Cookie cookie = new Cookie(LOGIN_COOKIE_NAME, scloginCookieVal);
        cookie.setPath("/");
        cookie.setMaxAge(expiry); // 设置超时时间s
        response.addCookie(cookie);
    }

    /**
     * 更新登录cookie
     * 
     * @Title updLoginCookie
     * @author 吕凯
     * @date 2019年7月20日 上午8:50:16
     * @param request
     * @param response
     * @return boolean
     */
    public static boolean updLoginCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie loginCookie = getLoginCookie(request);
        if (loginCookie != null) {
            loginCookie.setMaxAge(loginCookie.getMaxAge()); // 设置超时时间s
            String tokenEncry = loginCookie.getValue();
            try {
                String token = SecurityUtil.simpleDecrypt(tokenEncry);
                String username = StringUtils.substringBetween(token, COOKIE_NAME_USERNAME, COOKIE_NAME_PASSWORD); // 获取用户名
                String password = StringUtils.substringBetween(token, COOKIE_NAME_PASSWORD, COOKIE_NAME_TIMEUTIL); // 获取密码
                String timeUtil = DateUtil.getDateTimeString(DateUtil.addDate(new Date(), loginCookie.getMaxAge(), Calendar.SECOND)); // 获取到期时间
                String ip = WebUtil.getIpAddr(request);
                String scloginCookieVal = COOKIE_NAME_USERNAME + username + COOKIE_NAME_PASSWORD + password + COOKIE_NAME_TIMEUTIL
                        + timeUtil + COOKIE_NAME_IP + ip;
                tokenEncry = SecurityUtil.simpleEncrypt(scloginCookieVal);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            loginCookie.setValue(tokenEncry);
            response.addCookie(loginCookie);
            return true;
        }
        return false;
    }

    /**
     * 获取登录cookie并转换为user对象
     * 
     * @Title getLoginCookie
     * @author 吕凯
     * @date 2019年7月19日 下午5:50:16
     * @param request
     * @return SystemUser
     */
    public static SystemUser loginCookie2User(HttpServletRequest request, HttpServletResponse response) {
        SystemUser user = null;
        Cookie loginCookie = getLoginCookie(request);
        if (loginCookie != null) {
            String scloginCookieVal = loginCookie.getValue();
            scloginCookieVal = SecurityUtil.simpleDecrypt(scloginCookieVal);
            user = new SystemUser();
            user.setLoginCode(StringUtils.substringBetween(scloginCookieVal, COOKIE_NAME_USERNAME, COOKIE_NAME_PASSWORD)); // 获取用户名
            user.setPassword(StringUtils.substringBetween(scloginCookieVal, COOKIE_NAME_PASSWORD, COOKIE_NAME_TIMEUTIL)); // 获取密码
            String timeUtilStr = StringUtils.substringBetween(scloginCookieVal, COOKIE_NAME_TIMEUTIL, COOKIE_NAME_IP); // 获取到期时间
            String ipStr = StringUtils.substringAfter(scloginCookieVal, COOKIE_NAME_IP); // 获取ip
            Date timeUtil = DateUtil.str2dateTime(timeUtilStr);
            if (timeUtil == null || new Date().after(timeUtil)) { // 超过有效期则返回null
                removeLoginCookie(response); // 移除
                return null;
            }
            String ip = WebUtil.getIpAddr(request) + ""; // 不为null
            boolean checkIp = PropertiesModel.CONFIG.getBoolean("cookie.checkip", true);
            if (!ip.equals(ipStr)) {
                log.warn("ip not equal：token ip:" + ipStr + " request ip:" + ip);
                if (checkIp) { // 设置了检查ip，则直接移除
                    removeLoginCookie(response); // 移除
                    return null;
                }
            }
            return user;
        }
        return user;
    }

    /**
     * 获取登录信息cookie
     * 
     * @Title getLoginCookie
     * @author 吕凯
     * @date 2019年7月20日 上午8:43:41
     * @param request
     * @return Cookie
     */
    protected static Cookie getLoginCookie(HttpServletRequest request) {
        Cookie cookieReturn = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(LOGIN_COOKIE_NAME)) {
                    return cookie;
                }
            }
        }
        return cookieReturn;
    }

    /**
     * 移除登录cookie
     * 
     * @Title removeLoginCookie
     * @author 吕凯
     * @date 2019年7月19日 下午5:50:35
     * @param response
     *            void
     */
    public static void removeLoginCookie(HttpServletResponse response) {
        try {
            removeCookie(response, LOGIN_COOKIE_NAME);
        } catch (Exception e) {
            log.error("", e);
        }
    }

}
